// 2013-9-14下午02:32:42  net.betou.web.AgencyOrProxyDisplayDirective.java

package net.betou.web;

import static net.betou.trade.web.AdminContextInterceptor.PERMISSION_MODEL;

import java.io.IOException;
import java.util.Map;

import net.betou.trade.web.DBConstants;
import net.betou.web.freemaker.DirectiveUtils;

import org.apache.commons.lang.StringUtils;

import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateDirectiveModel;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;
import freemarker.template.TemplateModelException;
import freemarker.template.TemplateScalarModel;
import freemarker.template.TemplateSequenceModel;

/**
 * 是否显示机构或者代理商角色标签 如果是系统管理员，直接pass 步骤， 1. 获取当前管理员的权限，比对是否有机构或者代理商权限 2.
 * 接收identity, 如果identiy不为空，并且有权限, pass=true 3. identity 为空的，pass=true
 * 
 * @author 叶装装
 */
public class AgencyOrProxyDisplayDirective implements TemplateDirectiveModel{

	public static final String PARAM_SYSTEM = "system";
	public static final String PARAM_IDENTITY = "identity";

	public static final String AGENCY_URL = "/agent/v_list.jspx";
	public static final String PROXY_URL = "/proxy/v_list.jspx";

	@SuppressWarnings( "unchecked" )
	public void execute( Environment env, Map params, TemplateModel [ ] loopVars, TemplateDirectiveBody body ) throws TemplateException, IOException {

		Boolean system = DirectiveUtils.getBool( PARAM_SYSTEM, params );
		String identity = DirectiveUtils.getString( PARAM_IDENTITY, params );
		boolean pass = false;

		if( system ){
			pass = true;
		}else if( StringUtils.isBlank( identity ) ){
			pass = true;
		}else{
			TemplateSequenceModel perms = getPerms( env );
			String perm;
			for ( int i = 0, len = perms.size( ); i < len; i++ ){
				perm = ( ( TemplateScalarModel ) perms.get( i ) ).getAsString( );

				if( DBConstants.DEFINED_AGENCY_IDENTITY.equals( identity ) ){
					if( perm.equals( AGENCY_URL ) ){
						pass = true;
						break;
					}
				}
				
				if( DBConstants.DEFINED_PROXY_IDENTITY.equals( identity )){
					if( perm.equals( PROXY_URL ) ){
						pass = true;
						break;
					}
				}
			}

		}
		if( pass ){
			body.render( env.getOut( ) );
		}
	}

	private TemplateSequenceModel getPerms( Environment env ) throws TemplateModelException {
		TemplateModel model = env.getDataModel( ).get( PERMISSION_MODEL );
		if( model == null ){
			return null;
		}
		if( model instanceof TemplateSequenceModel ){
			return ( TemplateSequenceModel ) model;
		}else{
			throw new TemplateModelException( "'perms' in data model not a TemplateSequenceModel" );
		}

	}
}
